package JavaMultiThreadProgramming.Ch2;

/**
 * Created by wyao on 17-3-6.
 */
public class T001_SynchronizedMethodLockObject {
    public static void main(String[] args) {
        MyObject myObject = new MyObject();
        ThreadA a = new ThreadA(myObject);
        a.setName("a");
        ThreadB b = new ThreadB(myObject);
        b.setName("b");
        a.start();
        b.start();
    }
}

class MyObject {
    synchronized public void methodA() {
        try {
            System.out.println("methodA, threadName=" + Thread.currentThread().getName());
            Thread.sleep(5000);
            System.out.println("methodA end, endTime=" + System.currentTimeMillis());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    synchronized public void methodB() {
        try {
            System.out.println("methodB, threadName=" + Thread.currentThread().getName());
            Thread.sleep(5000);
            System.out.println("methodB end, endTime=" + System.currentTimeMillis());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class ThreadA extends Thread {
    private MyObject myObject;

    public ThreadA(MyObject myObject) {
        this.myObject = myObject;
    }

    public void run() {
        myObject.methodA();
    }
}

class ThreadB extends Thread {
    private MyObject myObject;

    public ThreadB(MyObject myObject) {
        this.myObject = myObject;
    }

    public void run() {
        myObject.methodB();
    }
}